package com.zzw.httpclient;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import java.net.URLEncoder;

public class LoginService extends Service {
    public LoginService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public static String loginByGet(String username, String password) {
        try {
            String path = "http://192.168.1.100:8080/web/LoginService?username="
                    + URLEncoder.encode(username, "utf-8") + "&password="
                    + URLEncoder.encode(password,"utf-8");
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            int code = conn.getResponseCode();
            if(code == 200){
                InputStream is = conn.getInputStream();
                String text = StreamUtil.readInputStream(is);
                return text;
            }else{
                return null;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static String loginByPost(String username, String password) {
        try {
            String path = "http://192.168.1.100:8080/web/LoginService";
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");

            String data = "username=" + URLEncoder.encode(username,"utf-8") +"&password="+
                    URLEncoder.encode(password,"utf-8");
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length",data.length()+"");

            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(data.getBytes());

            int code = conn.getResponseCode();
            if(code == 200){
                InputStream is = conn.getInputStream();
                String text = StreamUtil.readInputStream(is);
                return text;
            }else{
                return null;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
